#ifndef MAINWINDOW_H
#define MAINWINDOW_H

#include <QMainWindow>
#include <QTcpSocket>
#include <QSslSocket>
#include <QFile>
#include <QSignalMapper>
#include "packagebuffer.h"
#include "transferworker.h"
#include "SpinLock.h"

QT_BEGIN_NAMESPACE
namespace Ui { class MainWindow; }
QT_END_NAMESPACE

struct UploadFileInfo
{
    QFile file;
    int64_t fileSize;
    QString fileName;
    int64_t sentByte;
};

class MainWindow : public QMainWindow
{
    Q_OBJECT

public:
    MainWindow(QWidget *parent = nullptr);
    ~MainWindow();

private:
    bool isFileExist(QString filePath);

private slots:
    void on_pushButtonConnect_clicked();
    void on_pushButtonClose_clicked();
    void on_pushButtonPath_clicked();
    void on_pushButtonSend_clicked();

    void connected();
    void readyRead();
    void disconnected();
    void encrypted();
    void peerVerifyError(const QSslError &error);
    void modeChanged(QSslSocket::SslMode newMode);

    void receiveMsg(quint16 indx, quint16 msg);

private:
    bool packageProcess();
    bool fileUploadRequest();
    bool fileUploadResponse(uint8_t *data, uint16_t size);

signals:
    void stop();
    void sendMsg(quint16 indx, quint16 msg, qint64 start, quint32 length);

private:
    Ui::MainWindow *ui;
    QTcpSocket *tcpSocket; //通信套接字
    QThread *tranThreads;
    TransferWorker *tranWorks;
    PackageBuffer pkgBuffer;
    UploadFileInfo fileInfo;
    QString svrIp;
    uint16_t svrPort;
    uint16_t clntNum;
    bool useSSL;
    CSpinLock spinLock;
    uint16_t runThread;
    double timeStart;
    CSpinLock fileLock;

    QMetaObject::Connection conConnected;
    QMetaObject::Connection conReadyRead;
    QMetaObject::Connection conDisconnected;
    QMetaObject::Connection conEncrypted;
    QMetaObject::Connection conPeerVerifyError;
    QMetaObject::Connection conModeChanged;
};
#endif // MAINWINDOW_H
